/**
 * EditorActions for AIChat吉PT userscript.
 * Handles chat run actions and utility functions for editor interactions.
 */
import { showAiPanel } from "./UIComponents";

/**
 * Runs chat with selected code from the Monaco editor
 * @param {number} type - The type of chat action to run
 * @param {boolean} isAll - Whether to include all code files or just selected code
 * @param {Object} editor - The Monaco editor instance
 * @param {Function} chatFn - The chat function to run
 * @param {Object} editorElements - UI elements for editor
 * @param {Object} codeEditorController - The code editor controller
 */
export function chatRun(
  type,
  isAll = false,
  editor,
  chatFn,
  editorElements,
  codeEditorController
) {
  let value = "";
  if (isAll) {
    value = getFileDictCode(codeEditorController);
  } else {
    let select = editor.getSelection();
    value = editor.getModel().getValueInRange(select);
  }

  if (value) {
    chatFn(value, type, "", "", isAll);
    showAiPanel(editorElements);
  } else {
    codeEditorController.debugger._console.error(
      "[Chat吉PT]" + "请先用鼠标框选代码片段，再调用AI功能。"
    );
  }
}

/**
 * Runs customized chat with input from the user and/or selected code
 * @param {number} type - The type of chat action to run
 * @param {string} customText - Custom text to include in the chat
 * @param {Object} editor - The Monaco editor instance
 * @param {Function} chatFn - The chat function to run
 * @param {Object} editorElements - UI elements for editor
 */
export function chatCustomizeRun(
  type,
  customText,
  editor,
  chatFn,
  editorElements
) {
  try {
    let select = editor.getSelection();
    let value = editor.getModel().getValueInRange(select);

    if (value || customText) {
      chatFn(customText + value, type, customText, value);
      showAiPanel(editorElements);
    }
  } catch (error) {
    if (customText) {
      chatFn(customText, type, customText);
      showAiPanel(editorElements);
    }
  }
}

/**
 * Gets the file dictionary code from all files in the editor
 * @param {Object} codeEditorController - The code editor controller
 * @returns {string} - String containing all file info and contents
 */
export function getFileDictCode(codeEditorController) {
  const fileDict = codeEditorController._editorState.fileDict;
  let result = "";

  for (const key in fileDict) {
    if (fileDict.hasOwnProperty(key)) {
      const { name, text, isClient } = fileDict[key];
      result += `文件名: ${name}\n是否客户端: ${isClient}\n内容:\n${text}\n\n`;
    }
  }

  return result;
}

/**
 * Handles message receiving for iframe communication
 * @param {Event} event - The message event
 */
export function handleMessageReceive(event) {
  // 消息处理函数的保留，但移除了boxIframe相关的代码
  // 现在这个函数为空，但保留函数定义以避免引用错误
}
